package com.hup.utils.swing.ui;

import com.sun.java.swing.plaf.windows.WindowsSliderUI;

import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicSliderUI;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.Field;

/**
 * 实现pressed时,马上定位到准确value,并进入拖拽模式;
 * 看源码改的
 *
 * @author hugan
 * @date 2023/5/3
 */
public class MyWindowsSliderUI extends WindowsSliderUI {

    private final Field isDraggingField;

    public MyWindowsSliderUI(JSlider b) {
        super(b);
        try {
            isDraggingField = BasicSliderUI.class.getDeclaredField("isDragging");
            isDraggingField.setAccessible(true);
        } catch (NoSuchFieldException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    @Override
    protected void installListeners(JSlider slider) {
        super.installListeners(slider);
        slider.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (!SwingUtilities.isLeftMouseButton(e)) return;
                try {
                    isDraggingField.set(MyWindowsSliderUI.this, true);
                } catch (IllegalAccessException ex) {
                    throw new IllegalArgumentException(ex.getMessage());
                }
                scrollTimer.stop();//要停,否则松开后会跳
                trackListener.mouseDragged(e);
            }

            //BasicSliderUI.TrackListener,此方法本身就没正确处理其他按键Released的情况,所以会有小bug
            //@Override
            //public void mouseReleased(MouseEvent e) {
            //    super.mouseReleased(e);
            //}
        });
    }

}
